# -*- coding:utf-8 -*-
import webapp2
import jinja2
import json
import gaesession
from lxml import html as HtmlParser
import xml.etree.ElementTree as ET
from google.appengine.api import urlfetch
import time
import hashlib
TOKEN='wechattoken';
class WechatApp(gaesession.BaseSessionHandler):
	def get(self):
		timestamp = self.request.get('timestamp');
		nonce = self.request.get('nonce');
		signature = self.request.get('signature');
		echostr = self.request.get('echostr');
		strList = sorted([TOKEN,timestamp,nonce]);
		srcSecret = ''.join(strList);
		mySha1 = hashlib.sha1();
		mySha1.update(srcSecret);
		secret = mySha1.hexdigest();
		if echostr==secret:
			self.reponse.out.write(echostr);
		return;
	def post(self):
		msg = self.request.body;
		msgRoot = ET.fromstring(msg);
		toUserName = msgRoot.find('ToUserName').text;
		fromUserName = msgRoot.find('FromUserName').text;
		createTime = msgRoot.find('CreateTime').text;
		msgType = msgRoot.find('MsgType').text;
		content = msgRoot.find('Content').text;
		msgId = msgRoot.find('MsgId').text;
		reponse = 'Book Not Found';
		if msgType=='text':
			reponse = self.reponseText(fromUserName,toUserName,content);
		self.response.out.write(reponse);
	def reponseText(self,toUserName,fromUserName,query):
		timeStr = int(time.time());
		content = 'Book Not Found';
		if query.isdigit():
			books = self.serachFromDouBanByIsbn(query);
			if books is not None:
				book = books[0];
				content = u'你可以去'+book['storename']+u'买这本书['+book['title']+u']，价格为'+str(book['price'])+u'元，便宜了'+str(book['cutprice'])+u'元,购买链接'+book['link'];
			else:
				content = 'Book Found';
		else:
			content = 'Please input correct isbn.';
		responseStr = '''
				<xml>
 					<ToUserName><![CDATA[%s]]></ToUserName>
					 <FromUserName><![CDATA[%s]]></FromUserName>
					 <CreateTime>%d</CreateTime>
					 <MsgType><![CDATA[text]]></MsgType>
 					<Content><![CDATA[%s]]></Content>
 					<FuncFlag>0</FuncFlag>
 				</xml>
		''' % (toUserName,fromUserName,timeStr,content);
		return responseStr;
		

	def serachFromDouBanByIsbn(self,query):
		serverUrl = 'https://api.douban.com/v2/book/isbn/'+query;
		result = urlfetch.fetch(serverUrl);
		if result.status_code==200:
			bookjson = json.loads(result.content);
			doubanBook = bookjson['alt']+'buylinks';
			doubanBookName = bookjson['title'];
			#buylink-table
			bookBuyLinkPage= urlfetch.fetch(doubanBook);
			if bookBuyLinkPage.status_code==200:
				books = [];
				doc = HtmlParser.document_fromstring(bookBuyLinkPage.content);
				try:
					linkTable = doc.get_element_by_id("buylink-table");
					tbody = linkTable.findall("tr");
					if len(tbody)>0:
						firstRow = False;
						for tr in tbody:
							if firstRow==False:
								firstRow=True;
							else:
								book={};
								tds = tr.findall("td");
								book['storename'] = tds[1].text_content().strip();
								book['cutprice'] = float(tds[3].text_content().strip());
								book['price'] = float(tds[2].text_content().strip());
								buylinkEle = tds[2].find('a');
								book['link'] = buylinkEle.attrib["href"].strip();
								book['title'] = doubanBookName;
								books.append(book);

					else:
						return None;
				except Exception, e:
					return None;
				return books;
			else:
				return None;
		else:
			return None;
routes = [
    webapp2.Route('/wechat/api', handler=WechatApp, name='wechat'),
];
app = webapp2.WSGIApplication(routes,debug=True,config=gaesession.sessionconfig)